<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入名称" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="编号" prop="bm">
            <el-input v-model="form.bm" placeholder="请输入编号" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="题目类型" prop="px">
            <el-select v-model="form.dtTypeId" placeholder="请题目类型" clearable :style="{width: '100%'}">
              <el-option
                v-for="dict in typeList"
                :key="dict.id"
                :label="dict.name"
                :value="dict.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态">
            <el-select v-model="form.status" placeholder="请选择状态" clearable :style="{width: '100%'}">
              <el-option
                v-for="dict in statusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12" >
          <el-form-item label="客户端" v-hasRole="['admin']">
            <wx-client :client-id="form.wxClientId" @wx-client="wxClient"></wx-client>
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="性格特征" prop="ywtz">
        <vue-ueditor-wrap v-model="form.ywtz" :config="myConfig" ></vue-ueditor-wrap>
      </el-form-item>
      <el-form-item size="large">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { listJxrgfx, getJxrgfx, delJxrgfx, addJxrgfx, updateJxrgfx, exportJxrgfx } from "@/api/dt/jxrgfx";
import {listType} from "@/api/dt/type";
import WxClient from "@/views/components/wx-client/wx-client";
import {getToken} from "@/utils/auth";
import VueUeditorWrap from "vue-ueditor-wrap";

export default {
  components: {
    WxClient,
    VueUeditorWrap
  },
  data() {
    return {
      appendToBody: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 九型人格分析表格数据
      jxrgfxList: [],
      // 题库类型
      typeList: [],
      // 状态字典
      statusOptions: [{
        dictLabel: "启用",
        dictValue: "1"
      },{
        dictLabel: "禁用",
        dictValue: "0"
      }],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "性格名称不能为空", trigger: "blur" }
        ],
        bm: [
          { required: true, message: "性格编号不能为空", trigger: "blur" }
        ],
        ywtz: [
          { required: true, message: "欲望特质不能为空", trigger: "blur" }
        ],
        px: [
          { required: true, message: "对应序号不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "请选择状态", trigger: "blur" }
        ],
        type: [
          { required: true, message: "请选择题目类型", trigger: "blur" }
        ]
      },
      base_url: process.env.VUE_APP_BASE_API,
      //文件列
      fileList: [],
      // 设置上传的请求头部
      headers: {Authorization: "Bearer " + getToken()},
      //上传地址
      url: process.env.VUE_APP_BASE_API + "/common/upload",
      //是否禁用上传
      flag: false,
      //图片路径
      files: {path: ''},
      myConfig: {
        // 编辑器不自动被内容撑高
        autoHeightEnabled: false,
        // 初始容器高度
        initialFrameHeight: 540,
        // 初始容器宽度
        initialFrameWidth: '100%',
        //启用自动保存
        enableAutoSave: true,
        // 上传文件接口（这个地址是我为了方便各位体验文件上传功能搭建的临时接口，请勿在生产环境使用！！！部署在国外的服务器，如果无法访问，请自备梯子）
        serverUrl: process.env.VUE_APP_BASE_API + '/api/ueditor/controller?userId='+this.$store.getters.userInfo.userId,
        // serverUrl:'http://35.201.165.105:8000/controller.php',
        // UEditor 资源文件的存放路径，如果你使用的是 vue-cli 生成的项目，通常不需要设置该选项，vue-ueditor-wrap 会自动处理常见的情况，如果需要特殊配置，参考下方的常见问题2
        UEDITOR_HOME_URL: '/ueditor/',
        zIndex: 1
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询九型人格分析列表 */
    getList() {
      this.loading = true;
      console.log(this.$route.query.id);
      this.form.id = this.$route.query.id;
      if( this.form.id != "" && this.form.id != undefined && this.form.id != null){
        getJxrgfx(this.form.id).then(response => {
          this.form = response.data;
        });
      }
      listType({state: 1}).then(response => {
        this.typeList = response.rows;
      })
      this.loading = false;
    },
    // 状态字典翻译
    stateFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        bm: undefined,
        detail: undefined,
        px: undefined,
        dtTypeId: undefined,
        wxClientId: undefined,
        delFlag: undefined,
        createBy: undefined,
        createTime: undefined,
        updateBy: undefined,
        updateTime: undefined,
        status: "1",
        ywtz: undefined,
        jbks: undefined,
        shfg: undefined,
        rjgx: undefined
      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateJxrgfx(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                var location = '/dt/jxrgfx';
                this.$router.push({'path':location, name:'Jxrgfx', 'query': {}})
              }
            });
          } else {
            addJxrgfx(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                var location = '/dt/jxrgfx';
                this.$router.push({'path':location, name:'Jxrgfx', 'query': {}})
              }
            });
          }
        }
      });
    },

    /** 上传成功后的回调 */
    uploadSuccess(response, file, fileList) {
      console.log("11112"+ response.fileName);
      console.log(file);
      this.form.img = response.fileName
      this.files.path = response.fileName
      this.flag = true
    },

    /** 上传之前的校验 */
    checkUpload(file) {
      console.log("文件类型", file)
      const imgType = file.type
      //图片不大于2M
      const isLtSize = file.size / 1024 / 1024 < 2
      if (['image/png', 'image/jpeg', 'image/jpg', 'image/gif'].indexOf(imgType) === -1) {
        this.$message.error('上传图片只能是 JPG、PNG、GIF格式!')
        return false;
      }
      if (!isLtSize) {
        this.$message.error(`上传图片大小不能超过2MB!`)
        return false;
      }
    },
    handleRemove(file, fileList) {
      console.log(file, fileList);
    },
    wxClient(e){
      this.form.wxClientId = e;
    }
  }
};
</script>
<style>
.dialogClass {
  top: 2vh;
}
.avatar-uploader i {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader i:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.avatar {
  width: 100px;
  height: 100px;
  display: block;
}
</style>
